package org.supper.common.util;

import io.micrometer.core.instrument.util.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author huqi 2021/10/22
 */
@Slf4j
public class ThreadUtil {

    public static final int threadCount;

    private static ThreadUtil threadUtil;

    static {
        threadCount = Runtime.getRuntime().availableProcessors() * 2;
        threadUtil = new ThreadUtil();
    }

    public static ThreadUtil getThreadPoolFactory() {
        return threadUtil;
    }

    public  ExecutorService start(int threadCount, final String name) {
        if (threadCount < 0) {
            threadCount = ThreadUtil.threadCount;
        }
        return new ThreadPoolExecutor(1, threadCount, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public void stop(final ExecutorService executorService) {
        if (executorService != null) {
            try {
                executorService.shutdown();
                while (!executorService.awaitTermination(1L, TimeUnit.SECONDS) && !executorService.isShutdown() && !executorService.isTerminated()) {
                    executorService.shutdown();
                }
            }
            catch (Exception e) {
                log.error("executor service stop error.msg:" + e.getStackTrace().toString());
            }
        }
    }

    public void stopNow(final ExecutorService executorService) {
        if (executorService != null) {
            try {
                executorService.shutdownNow();
                while (!executorService.awaitTermination(1L, TimeUnit.SECONDS) && !executorService.isShutdown() && !executorService.isTerminated()) {
                    executorService.shutdownNow();
                }
            }
            catch (Exception e) {
                log.error("executor service stop now error.msg:" + e.getStackTrace().toString());
            }
        }
    }
}
